package com.rr.security.filter;

import com.rr.dao.UserDao;
import com.rr.security.AuthTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author RR
 * @date 2023/3/15 20:01
 */
/*
 * 授权过滤器
 * */
public class AuthFilter extends BasicAuthenticationFilter {

    private AuthTokenManager authTokenManager;
    private UserDao userDao;

    public AuthFilter(AuthenticationManager authenticationManager, AuthTokenManager authTokenManager, UserDao userDao) {
        super(authenticationManager);
        this.authTokenManager = authTokenManager;
        this.userDao = userDao;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        String username = authTokenManager.getUsername(token);
        if (!StringUtils.isEmpty(username)) {
            User user = userDao.getUser(username);
            if (user != null) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request,response);
    }

}
